package libcore.kotpref

import android.content.SharedPreferences
import java.lang.IllegalArgumentException
import java.lang.reflect.ParameterizedType
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

class KotPrefProperty<T>(private val key: String, private val defaultValue: T) :
    ReadWriteProperty<KotPrefBase, T> {
    override fun getValue(thisRef: KotPrefBase, property: KProperty<*>): T {
        return getValue(thisRef.sharedPreferences, key, defaultValue)
    }

    override fun setValue(thisRef: KotPrefBase, property: KProperty<*>, value: T) {
        putValue(thisRef.sharedPreferences.edit(), key, value)
    }

    private fun getValue(sp: SharedPreferences, key: String, defaultValue: T): T {
//        return sp.all?.getOrDefault(key,defaultValue) as? T
        // todo 这里如何能获取泛型的类型
        val type = (this.javaClass.genericInterfaces[0] as ParameterizedType).actualTypeArguments[1]
        println(">> type = $type") // type = T，这里还是拿不到具体的泛型类型
        return when (defaultValue) {
            is Int -> sp.getInt(key, defaultValue)
            is Long -> sp.getLong(key, defaultValue)
            is Float -> sp.getFloat(key, defaultValue)
            is Boolean -> sp.getBoolean(key, defaultValue)
            is String? -> sp.getString(key, defaultValue)
            else -> error("未知类型")
        } as T
    }

    private fun putValue(sp: SharedPreferences.Editor, key: String, value: T) {
        when (value) {
            is Int -> sp.putInt(key, value)
            is Long -> sp.putLong(key, value)
            is Float -> sp.putFloat(key, value)
            is Boolean -> sp.putBoolean(key, value)
            is String? -> sp.putString(key, value)
            else -> error("未知类型")
        }.commit()
    }


}